/**
 * Created by user on 17/2/15.
 */
let request_agent = require('request-promise');
let utils = require('../utils');

module.exports = exports.default = class ServiceRequest {

    constructor(appId, isDev = 0) {
        this.appId = appId;
        this.headers = {
            'User-Agent': 'node-request',
            'Content-Type': 'application/json'
        };
    }

    async _buildUrl(act_url) {
        let address = await utils.getEndpoint(this.appId);
        this.base_url = `http://${address.ip}:${address.port}`;
        if (act_url.indexOf('/') >= 0) {
            return this.base_url + act_url;
        } else {
            return `${this.base_url}/${act_url}`;
        }
    }

    header(headers) {
        this.headers = Object.assign(this.headers, headers);

        return this;
    }

    async get(act_url, query = {}) {
        let options = {
            uri: await this._buildUrl(act_url),
            qs: query,
            headers: this.headers,
            json: true
        };
        return await request_agent(options);
    }

    async post(act_url, data = {}) {
        let options = {
            method: 'POST',
            uri: await this._buildUrl(act_url),
            body: data,
            headers: this.headers,
            json: true
        };
        return await request_agent(options);
    }
};
